import 'package:get/get.dart';
// import 'package:xin_he/page/shopping_car/models/xin_he_goods_model.dart';
import 'package:xin_he/page/shopping_car/xin_he_shopping_car/xin_he_shop_cart_goods_entity.dart';
import 'package:xin_he/routes/xin_he_routes.dart';
import 'package:xin_he/utils/xin_he_user_data.dart';

import '../../../service/xin_he_reqest.dart';
import '../../../utils/xin_he_event_bus.dart';
import '../../../utils/xin_he_storage.dart';
import '../../../utils/xin_he_toast.dart';
import 'xin_he_shopping_car_state.dart';

class XinHeShoppingCarLogic extends GetxController {
  final XinHeShoppingCarState state = XinHeShoppingCarState();


  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    requestShopCart();

    bus.on(XinHeStorage.refreshCart, (arg){
      requestShopCart();
    });

    //用户资料变更成功事件通知
    bus.on(XinHeStorage.KdUserInfoUpdateSuc, (arg) async {
      //登录成功后更新用户数据,刷新页面
      update();
      requestShopCart();

    });
    //收到退出登录成功通知
    bus.on(XinHeStorage.KdUserLogoutNoti, (arg) {
      //退出成功后重置用户数据和app状态，刷新页面
      update();
      requestShopCart();

    });

    bus.on(XinHeStorage.KNeedRefresh, (arg) {

      if(arg == 3) {
        update();
        // requestShopCart();
      }

    });
  }

  void handleAllItems(bool isSelected) {
      for(XinHeShopCartGoodsEntity e in state.allItemsList){
        e.isSelected= isSelected;
        for(XinHeShopCartGoodsOrderItems el in e.orderItems! ) {
          el.isSelected = isSelected;
        }
      }

      _calculateTotalGoodsCountAndPrice();

  }

  void handleGoods(int index) {
    // XinHeShopCartGoodsEntity model = state.allItemsList[index];
    // model.isSelected = !model.isSelected;
    // for( XinHeShopCartGoodsOrderItems e in model.orderItems!) {
    //   e.isSelected = model.isSelected;
    // }
    // state.allItemsList[index] = model;


    for(int i = 0; i< state.allItemsList.length; i++) {

      XinHeShopCartGoodsEntity mod = state.allItemsList[i];

      if(i == index) {
        mod.isSelected = !mod.isSelected;
        for( XinHeShopCartGoodsOrderItems e in mod.orderItems!) {
          e.isSelected = mod.isSelected;
        }
      }else {
        mod.isSelected = false;
        for( XinHeShopCartGoodsOrderItems e in mod.orderItems!) {
          e.isSelected = false;
        }
      }

      state.allItemsList[i] = mod;

    }

    _calculateTotalGoodsCountAndPrice();
  }

  void handleGoodsItem(int index, int fatherIndex){
    XinHeShopCartGoodsEntity model = state.allItemsList[fatherIndex];
    XinHeShopCartGoodsOrderItems itemModel = model.orderItems![index];



    for(int i = 0; i< state.allItemsList.length; i++) {

      XinHeShopCartGoodsEntity mod = state.allItemsList[i];

      if(i == fatherIndex) {
        for(int j= 0; j< mod.orderItems!.length; j++ ) {

          if(j == index) {
            XinHeShopCartGoodsOrderItems itemM = mod.orderItems![index];
            itemM.isSelected = !itemM.isSelected;
          }
        }

        bool isExistUnselected = false;
        for( XinHeShopCartGoodsOrderItems e in mod.orderItems!) {

          if(e.isSelected == false) {
            isExistUnselected = true;
            break;
          }
        }
        if(isExistUnselected == true) {
          mod.isSelected = false;
        }else {
          mod.isSelected = true;
        }

      }else {
        mod.isSelected = false;
        for( XinHeShopCartGoodsOrderItems e in mod.orderItems!) {
          e.isSelected = false;
        }
      }

      state.allItemsList[i] = mod;

    }


    // for(int i = 0; i< state.allItemsList.length; i++) {
    //   XinHeShopCartGoodsEntity mod = state.allItemsList[i];
    //   if(i == fatherIndex) {
    //     bool isExistUnselected = false;
    //     for( XinHeShopCartGoodsOrderItems e in mod.orderItems!) {
    //
    //       if(e.isSelected == false) {
    //         isExistUnselected = true;
    //         break;
    //       }
    //     }
    //     if(isExistUnselected == true) {
    //       mod.isSelected = false;
    //     }else {
    //       mod.isSelected = true;
    //     }
    //   }
    //   state.allItemsList[i] = mod;
    //
    // }





    // itemModel.isSelected = !itemModel.isSelected;
    // model.orderItems![index] = itemModel;
    //
    // if(itemModel.isSelected == true) {
    //   model.isSelected = itemModel.isSelected;
    // }else {
    //   bool modelSelected = false;
    //   for( XinHeShopCartGoodsOrderItems e in model.orderItems!) {
    //     if(e.isSelected) {
    //       modelSelected = true;
    //       break;
    //     }
    //   }
    //   if(modelSelected == false) {
    //     model.isSelected = false;
    //   }else {
    //     model.isSelected = true;
    //   }
    // }
    //
    // state.allItemsList[fatherIndex] = model;

    _calculateTotalGoodsCountAndPrice();
  }

  // void handleItemCount(int index,bool isAdd){
  //   XinHeShopCartGoodsEntity model = state.allItemsList[index];
  //
  //   if(isAdd){
  //     // model.goo ++;
  //   }else {
  //     // model.count --;
  //
  //   }
  //
  //   state.allItemsList[index] = model;
  //   // if(model.count ==0) state.allItemsList.remove(model);
  //
  //   _calculateTotalGoodsCountAndPrice();
  // }


  void _calculateTotalGoodsCountAndPrice() {
    state.selectedItemsList.clear();

    for(XinHeShopCartGoodsEntity e in state.allItemsList){

      if(e.isSelected){
        state.selectedItemsList.add(e);
      }else {
        for(XinHeShopCartGoodsOrderItems el in e.orderItems!) {
          if(el.isSelected){
            state.selectedItemsList.add(e);
            break;
          }
        }
      }

    }

    double totalAmount = 0;
    int totalTypeCount = 0;
    for(XinHeShopCartGoodsEntity e in state.selectedItemsList){
      for(XinHeShopCartGoodsOrderItems ie in e.orderItems!) {
        if(ie.isSelected) {
          totalAmount = totalAmount + (ie.goodsPrice!) * ie.goodsAmount!;
          totalTypeCount++;
        }
      }
    }

    state.totalPrice.value = totalAmount;
    state.goodsTypeCount.value =  totalTypeCount;


    bool isAllSelected = true;
    if(state.selectedItemsList.isEmpty) {
      state.isAllButtonSelected.value = false;

    }else {
      for(XinHeShopCartGoodsEntity e in state.selectedItemsList){
        for(XinHeShopCartGoodsOrderItems ie in e.orderItems!) {
          if(ie.isSelected == false) {
            isAllSelected = false;
            break;
          }
        }
      }

      state.isAllButtonSelected.value = isAllSelected;
    }




   // if(state.selectedItemsList.length == state.allItemsList.length){
   //   state.isAllButtonSelected.value = true;
   //
   // }else {
   //   state.isAllButtonSelected.value = false;
   // }

  }


  toPay(){
    if(state.goodsTypeCount.value == 0){
      XinHeToast.center('请添加商品');
      return;
    }
    Map map = {
      'list':state.selectedItemsList.value,
      'totalAmount':state.totalPrice.value,
      'count': state.goodsTypeCount.value
    };
    Get.toNamed(XinHeRoutes.sureOrder,arguments: map);
  }

  ///查询购物车
  requestShopCart() async {


    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);
    Map<String,dynamic> ss = { 'userId': userId };

    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/shopcart/findShopcart',params: ss,isPost: false);
    if(!result.result || result.data['code'] != 0) {
      XinHeToast.center(result.data['message']);
      return ;
    }

    List dataList = result.data['data'] ??[];
    List modalArr = [];
    if(dataList.isNotEmpty) {
      for(var e in dataList) {
        XinHeShopCartGoodsEntity model = XinHeShopCartGoodsEntity.fromJson(e);
        modalArr.add(model);
      }

      state.allItemsList.value = modalArr;

    }else {
      state.allItemsList.clear();
    }

    state.selectedItemsList.clear();
    state.isAllButtonSelected.value = false;
    state.totalPrice.value = 0.0;
    state.goodsTypeCount.value = 0;


  }

  ///修改购物车商品数量
  modifyGoodsNumberShopCart(XinHeShopCartGoodsOrderItems model, bool isAdd,int index,int fatherIndex) async {


    var count = model.goodsAmount!;

    if(isAdd) {
      count++;
    }else {
      if(count == 0) return ;
      count--;
    }

    Map<String,dynamic> ss = {
         'amount': count,
         'orderItemId': model.orderItemId

    };

    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/shopcart/saveShopcartAmount',params: ss,isPost: true,isPostAndwwwForm: true);
    if(!result.result || result.data['code'] != 0) {
      XinHeToast.center(result.data['message']);
      return ;
    }

    XinHeShopCartGoodsEntity entity =  state.allItemsList[fatherIndex];

    if(count == 0) {

      if(entity.orderItems?.length == 1){
        state.allItemsList.remove(entity);
      }else {
        entity.orderItems?.remove(model);
      }

    }else {
      model.goodsAmount = count;

      entity.orderItems![index] = model;

      state.allItemsList[fatherIndex] = entity;
    }



  }


}
